package com.itheima.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SmsUtil {
    private static final Logger logger = LoggerFactory.getLogger(SmsUtil.class);

    @Value("${alibaba.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${alibaba.sms.accessKeySecret}")
    private String accessKeySecret;

    @Value("${alibaba.sms.signName}")
    private String signName;

    @Value("${alibaba.sms.templateCode}")
    private String templateCode;

    @Value("${alibaba.sms.endpoint}")
    private String endpoint;

    private Client client;

    @PostConstruct
    public void init() {
        try {
            client = createClient(accessKeyId, accessKeySecret, endpoint);
            logger.info("SMS client initialized successfully.");
        } catch (Exception e) {
            logger.error("Failed to initialize SMS client: {}", e.getMessage(), e);
            throw new RuntimeException("Failed to initialize SMS client: " + e.getMessage(), e);
        }
    }

    public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret)
                .setEndpoint(endpoint);
        return new Client(config);
    }

    public SendSmsResponse sendSms(String phoneNumber, String templateParam) {
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam(templateParam);

            SendSmsResponse response = client.sendSms(sendSmsRequest);
            logger.info("SMS sent successfully to phone number: {}", phoneNumber);
            return response;
        } catch (Exception e) {
            logger.error("Failed to send SMS to phone number {}: {}", phoneNumber, e.getMessage(), e);
            throw new RuntimeException("Failed to send SMS: " + e.getMessage(), e);
        }
    }
}
